package com.hschinese.pronunciation.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.hschinese.pronunciation.R;
import com.hschinese.pronunciation.bean.UserInfo;
import com.hschinese.pronunciation.model.UserInfoModel;
import com.hschinese.pronunciation.utils.Constant;
import com.hschinese.pronunciation.utils.Logger;
import com.hschinese.pronunciation.utils.MD5Utils;
import com.hschinese.pronunciation.utils.SharedPreferenceUtils;
import com.hschinese.pronunciation.utils.UIUtils;
import com.hschinese.pronunciation.utils.UrlUtil;
import com.hschinese.pronunciation.utils.Utils;
import com.hschinese.pronunciation.utils.WebRequestUtil;
import com.hschinese.pronunciation.widget.Header;
import com.hschinese.pronunciation.widget.HsDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.security.NoSuchAlgorithmException;
import java.util.HashMap;

public class RegisterActivity extends BaseActivity implements View.OnClickListener{
    private Header mHeader = null;
    private TextView mRegister = null;
    private EditText mEmail, mPassword, mPasswordConfirm;
    private TextView mGotoLogin;
    private HsDialog mDialog = null;

    private SharedPreferenceUtils mSharedPrefUtil;
//    private int mStartActivityId = 1;
    private boolean isLogined = false;
    private boolean isFromMore = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        isFromMore = getIntent().getBooleanExtra("is_create_profile", false);
        initViews();

//        mStartActivityId = getIntent().getIntExtra("start_activity", 0);
        mSharedPrefUtil = SharedPreferenceUtils.getInstance(RegisterActivity.this);
        isLogined = mSharedPrefUtil.getIsLogined();
    }

    private void initViews() {
        mHeader = (Header)findViewById(R.id.reg_header);
        if (isFromMore) {
            mHeader.setTitle(getResources().getString(R.string.create_person_profile));
        } else {
            mHeader.setTitle(getResources().getString(R.string.register_title));
        }
        mHeader.setLeftClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mRegister = (TextView)findViewById(R.id.reg_register);
        mRegister.setOnClickListener(this);

        mEmail = (EditText)findViewById(R.id.reg_email_edit);
        mPassword = (EditText)findViewById(R.id.reg_pwd_edit);
        mPasswordConfirm = (EditText)findViewById(R.id.reg_pwd_edit_confirm);

        mGotoLogin = (TextView)findViewById(R.id.reg_goto_login);
        mGotoLogin.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        mGotoLogin.setOnClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void finish() {
        super.finish();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.reg_register) {
            register();
        } else if (id == R.id.reg_goto_login) {
            if (isFromMore) {
                Intent it = new Intent(RegisterActivity.this, LoginActivity.class);
                startActivity(it);
            }
            this.finish();
        }
    }

    private void showWaitDialog() {
        mDialog = new HsDialog(RegisterActivity.this, R.style.pop_dialog, getResources().getString(R.string.login_dlg_msg), true, false);
        mDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                WebRequestUtil.getInstance(RegisterActivity.this).cancelByTag(UrlUtil.LOGIN);
            }
        });
        mDialog.show();
    }

    private void register() {
        String email = mEmail.getText().toString();
        String pwd = mPassword.getText().toString();
        String pwdConfirm = mPasswordConfirm.getText().toString();
        // Check email
        if (TextUtils.isEmpty(email)) {
            UIUtils.showToast(RegisterActivity.this, getResources().getString(R.string.empty_email), Toast.LENGTH_SHORT);
            return;
        } else if (TextUtils.isEmpty(pwd)) {
            UIUtils.showToast(RegisterActivity.this, getResources().getString(R.string.empty_pwd), Toast.LENGTH_SHORT);
            return;
        } else if (TextUtils.isEmpty(pwdConfirm)) {
            UIUtils.showToast(RegisterActivity.this, getResources().getString(R.string.pwd_confirm), Toast.LENGTH_SHORT);
            return;
        } else if (!pwd.equals(pwdConfirm)) {
            UIUtils.showToast(RegisterActivity.this, getResources().getString(R.string.pwd_confirm_failed), Toast.LENGTH_SHORT);
            return;
        }
        String apkey =  null;
        showWaitDialog();
        registerRequest(email, pwd);
    }

    private void registerRequest(String email, String pwd) {
        String url = "";
        String apkey = "";
        HashMap<String, String> params = new HashMap<String, String>();

        params.put("email", email);
        params.put("password", pwd);
        params.put("language", Utils.getLanguage(RegisterActivity.this));
        params.put("mckey", Utils.getUniqueCode(RegisterActivity.this));
        if(isLogined) { // 创建个人档
            url = UrlUtil.CREATE_PROFILES;
            String nemail = mSharedPrefUtil.getuserInfo().getNemail();
            Logger.e("xionghy - nemail: " + nemail);
            params.put("nemail", nemail);
            params.put("comefrom", Constant.PRODUCT_ID);
            try {
                apkey = MD5Utils.getMD5(Constant.PRODUCT_ID + Utils.getUniqueCode(RegisterActivity.this) + nemail + email + pwd + "hansheng");
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            if (apkey == null) {
                UIUtils.showToast(RegisterActivity.this, "生成apkey失败。", Toast.LENGTH_SHORT);
                return;
            }
        } else {
            url = UrlUtil.REGISTER;
            params.put("productID", Constant.PRODUCT_ID);
            try {
                apkey = MD5Utils.getMD5(email + Constant.PRODUCT_ID + "hansheng");
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            if (apkey == null) {
                UIUtils.showToast(RegisterActivity.this, "生成apkey失败。", Toast.LENGTH_SHORT);
                return;
            }
        }
        params.put("apkey", apkey.toUpperCase());
        WebRequestUtil.getInstance(RegisterActivity.this).postRequestString(url, params, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    JSONObject json = new JSONObject(s);
                    boolean b = json.getBoolean("Success");
                    if (b) {
                        Logger.e("xionghy -- login response: " + json.toString());
                        JSONObject js = json.getJSONObject("User");
                        registerSuccess(js);
                    } else {
                        String msg = Utils.delHTMLTag(json.getString("Message"));
                        UIUtils.showToast(RegisterActivity.this, msg, Toast.LENGTH_SHORT);
                        Logger.e("xionghy -- login response: " + json.getString("Message"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } finally {
                    mDialog.dismiss();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Logger.e("xionghy -- login response: " + volleyError.getMessage());
                mDialog.dismiss();
            }
        });
    }

    private void registerSuccess(JSONObject json) throws JSONException{
        try {
            UserInfo userInfo = UserInfoModel.getInstance().getUserInfoObj(json);
            // TODO save data to shared preference.
            mSharedPrefUtil.setIsLogined(true);
            mSharedPrefUtil.setUserInfo(userInfo);
            // TODO 如果启动页面是MainActivity，则直接调转到EntryActivity
//            if (mStartActivityId == 1) {
                Intent it = new Intent(RegisterActivity.this, EntryActivity.class);
                it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(it);
//            }
            this.finish();
        } catch (JSONException e) {
            Logger.e("xionghy - Login failed. User Data Translate Failed.");
            e.printStackTrace();
        }
    }
}
